<template>
	<view class="login_box">
		<view class="text_login">
			<!-- logo -->
			<image class="login_logo"  src="../../static/logo/orange.png" alt="" />
			
			<!-- 表单区域 -->
			<view class="login_phone">
				<text>手机号</text>
				<input v-model="phone" type="text"  maxlength="11" />
			</view>
			<view class="login_code">
				<text>验证码</text>
				<input v-model="code" type="text"  maxlength="4" />
				<view hover-class="touchOpacity" @click="getCode" >{{msg}}</view>
			</view>
			
			<!-- 登录按钮 -->
			<view class="login_but" hover-class="touchOpacity" @click="login" >
				<text space="ensp">登    录</text> 
			</view>
		</view>
	</view>
</template>

<script>

	export default {
		data() {
			return {
				phone:'13623834167',
				code:'',
				msg:'获取验证码',
				tag:false
			}
		},
		onUnload() {
			// 生命周期  销毁页面
			uni.removeStorageSync('phone');
			uni.removeStorageSync('code');
		},
		methods: {
			async login(){
				
				let oldPhone = uni.getStorageSync('phone')
				let oldCode = uni.getStorageSync('code')

				if(this.phone != oldPhone || this.code != oldCode){
					uni.showToast({
						title:'手机号或验证码不正确',
						icon:'none'
					})
					return
				}
				
				let res = await this.$http({
					url:'smslogin',
					method:'post',
					data:{
						phone:this.phone
					}
				})
				console.log(res.data);
				if(res.data.code === 200){
					uni.showToast({
						title:res.data.msg,
						icon:'none'
					})
					// 登录成功  存储本地缓存
					uni.setStorageSync('userInfo',res.data.list);
					// 获取当前页面栈
					// let page = getCurrentPages()
					// console.log(page);
					
					// uni.switchTab({
					// 	url:'../index/index'
					// })
					
					setTimeout(()=>{
						// #ifndef MP-WEIXIN
						uni.navigateBack({
							delta:1
						})
						// #endif
						
						// #ifdef MP-WEIXIN
						uni.reLaunch({
							url:'../index/index'
						})
						// #endif
						
						
					},1000)
					
				}
				
				
				
			},
			// 获取验证码
			async getCode(){
				// 防止定时器重复触发 
				if(this.tag) return
				// 1.获取手机号
				let phone = this.phone
				// 2.验证手机号
				let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
				if(!reg.test(phone)){
					uni.showToast({
						title:'手机号格式不正确',
						icon:'none'
					})
					return
				}
				console.log('手机号合法');
				
				let res = await this.$http({
					url:'sms',
					data:{
						phone:this.phone
					}
				})
				console.log(res);
				if(res.data.code === 200){
					let n = 5;
					let timer = setInterval(()=>{
						this.tag = true
						n--;
						this.msg = n + '秒后重新发送'
						if(n<0){
							this.msg = '获取验证码';
							clearInterval(timer)
							this.tag = false
						}
					},1000)
					
					// 存到缓存-- 点击登录, 验证手机号以及验证码 输入是否正确
					uni.setStorageSync('code',res.data.list.code)
					uni.setStorageSync('phone',phone)
				}
			}
		}
}
</script>

<style>
	/* 引入样式 */
	@import url("@/static/css/textlogin.css");
</style>
